package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.*;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {
    @Autowired
    private EmpService empService;
    @Override
    public PageResult<Clazz> getPageResult(String name, LocalDate begin, LocalDate end, int page, int pageSize) {
        Page<Clazz> page2= new Page<>(page, pageSize);
        page2.addOrder(OrderItem.desc("create_time"));
        page2 = page(page2);
        // 获取班级集合
        List<Clazz> clazzes = page2.getRecords();
        //获取所有班级班主任id
        Set<Integer> masterIds = clazzes.stream().map(Clazz::getMasterId).collect(Collectors.toSet());
        //批量查询这些班主任信息
        List<Emp> emps = empService.listByIds(masterIds);
        //将班主任信息封装到班级对象中
        clazzes.forEach(clazz -> {
            emps.forEach(emp -> {
                if (clazz.getMasterId() != null && clazz.getMasterId().equals(emp.getId())) {
                    clazz.setMasterName(emp.getName());
                }
            });
        });
        return new PageResult<>(page2.getTotal(), page2.getRecords());
    }
}
